class TestCaseGenerator {
    constructor() {
        this.init();
        this.bindEvents();
        // 默认激活测试用例生成模块
        this.activateModule('testCaseGen');
    }

    async init() {
        const moduleHTML = `
            <div id="testCaseGen" class="module-content active">
                <div class="file-upload-section">
                    <h2>测试用例生成</h2>
                    <div class="upload-container">
                        <input type="file" id="codeFileInput" accept=".pdf,.docx,.doc,.txt" style="display: none;">
                        <button class="file-upload-btn" id="uploadBtn">选择文件</button>
                        <div class="file-name" id="fileName"></div>
                    </div>
                    <button class="generate-btn" id="generateBtn" disabled>生成测试用例</button>
                </div>
                <div class="result-section" id="resultSection" style="display: none;">
                    <h3>生成的测试用例：</h3>
                    <table id="testCaseTable">
                        <thead>
                            <tr>
                                <th>模块</th>
                                <th>测试点</th>
                                <th>前置条件</th>
                                <th>测试步骤</th>
                                <th>预期结果</th>
                            </tr>
                        </thead>
                        <tbody id="testCaseTableBody"></tbody>
                    </table>
                </div>
            </div>
        `;

        // 将模块内容添加到主内容区域
        const mainContent = document.querySelector('.main-content');
        mainContent.insertAdjacentHTML('beforeend', moduleHTML);

        // 初始化元素引用
        this.fileInput = document.getElementById('codeFileInput');
        this.uploadBtn = document.getElementById('uploadBtn');
        this.fileNameDisplay = document.getElementById('fileName');
        this.generateBtn = document.getElementById('generateBtn');
        this.resultSection = document.getElementById('resultSection');
        this.testCaseTableBody = document.getElementById('testCaseTableBody');
        this.testCaseResult = document.getElementById('testCaseResult');

        // 高亮侧边栏中的测试用例生成选项
        const sidebarItems = document.querySelectorAll('.sidebar-menu li');
        sidebarItems[0].classList.add('active');
    }

    bindEvents() {
        // 文件上传按钮点击事件
        this.uploadBtn.addEventListener('click', () => {
            this.fileInput.click();
        });

        // 文件选择变化事件
        this.fileInput.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file) {
                // 验证文件类型
                const validTypes = ['.pdf', '.docx', '.doc', '.txt'];
                const fileExtension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
                
                if (validTypes.some(type => fileExtension.endsWith(type))) {
                    this.fileNameDisplay.textContent = `已选择文件: ${file.name}`;
                    this.generateBtn.disabled = false;
                    console.log('文件已选择:', file.name);
                } else {
                    alert('请选择有效的文件类型 (PDF, DOCX, DOC, TXT)');
                    this.fileInput.value = ''; // 清除选择
                    this.fileNameDisplay.textContent = '';
                    this.generateBtn.disabled = true;
                }
            } else {
                this.fileNameDisplay.textContent = '';
                this.generateBtn.disabled = true;
            }
        });

        // 生成测试用例按钮点击事件
        this.generateBtn.addEventListener('click', () => {
            this.generateTestCases();
        });

        // 侧边栏模块切换事件
        const sidebarItems = document.querySelectorAll('.sidebar-menu li');
        sidebarItems.forEach((item, index) => {
            item.addEventListener('click', () => {
                this.activateModule(index === 0 ? 'testCaseGen' : `module${index}`);
                sidebarItems.forEach(i => i.classList.remove('active'));
                item.classList.add('active');
            });
        });
    }

    activateModule(moduleId) {
        // 隐藏所有模块
        document.querySelectorAll('.module-content').forEach(module => {
            module.classList.remove('active');
        });
        // 显示选中的模块
        const activeModule = document.getElementById(moduleId);
        if (activeModule) {
            activeModule.classList.add('active');
        }
    }
    async generateTestCases() {
        const file = this.fileInput.files[0];
        if (!file) {
            alert('请先选择文件');
            return;
        }
    
        // 显示加载状态
        this.generateBtn.disabled = true;
        this.generateBtn.textContent = '生成中...';
        this.resultSection.style.display = 'none';
    
        try {
            const formData = new FormData();
            formData.append('file', file);
            console.log('正在上传文件:', file.name);
    
            // 调用后端API生成测试用例
            const response = await fetch('/generate-test-cases', {
                method: 'POST',
                body: formData
            });
    
            if (!response.ok) {
                const errorData = await response.json();
                const errorMsg = errorData.error || `HTTP错误! 状态码: ${response.status}`;
                if (errorData.error && errorData.error.includes('余额不足')) {
                    throw new Error('API余额不足，请联系管理员');
                }
                throw new Error(errorMsg);
            }
    
            // 解析后端返回的JSON数据
            const result = await response.json();
            // 直接使用后端返回的测试用例数据
            console.log('收到服务器响应:', result);
            
            if (result && Array.isArray(result.test_cases)) {
                // 清空现有表格内容
                this.testCaseTableBody.innerHTML = '';

                // 填充表格数据
                result.test_cases.forEach(testCase => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${testCase.模块 || ''}</td>
                        <td>${testCase.测试点 || ''}</td>
                        <td>${testCase.前置条件 || ''}</td>
                        <td>${(testCase.测试步骤 || '').replace(/\n/g, '<br>')}</td>
                        <td>${testCase.预期结果 || ''}</td>
                    `;
                    this.testCaseTableBody.appendChild(row);
                });

                this.resultSection.style.display = 'block';
            } else {
                throw new Error(result.error || '未知错误');
            }
        } catch (error) {
            console.error('Error:', error);
            this.resultSection.style.display = 'block';
            this.testCaseResult.innerHTML = `<div class="error-alert">
                    <span class="error-icon">❗</span>
                    <div class="error-content">
                        <h4>操作失败：${error.message}</h4>
                        <p>${error.message.includes('API') ? '请检查API密钥或联系管理员' : '请检查文件格式或网络连接'}</p>
                    </div>
                </div>`;
        } finally {
            // 恢复按钮状态
            this.generateBtn.disabled = false;
            this.generateBtn.textContent = '生成测试用例';
        }
    }
    formatCSVContent(csvText) {
        try {
            const rows = csvText.split('\n');
            let formattedContent = '';
            
            rows.forEach((row, index) => {
                if (index === 0) {
                    formattedContent += '【测试用例】\n';
                    formattedContent += row + '\n';
                    formattedContent += '='.repeat(80) + '\n';
                } else if (row.trim()) {
                    formattedContent += row + '\n';
                }
            });

            return formattedContent;
        } catch (error) {
            console.error('格式化CSV内容时出错:', error);
            return csvText; // 如果格式化失败，返回原始内容
        }
    }

    readFile(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = (e) => resolve(e.target.result);
            reader.onerror = (e) => reject(e);
            reader.readAsText(file);
        });
    }
}